'use strict';

const semver = require('semver')
const colors = require('colors')

const log = require('@cjx-cli-dev/log')
const { isArray } = require('@cjx-cli-dev/utils')

// 要求最低的node版本
const LOWEST_NODE_VERSION = '12.0.0'

class Command {
  constructor(argv) {
    // console.log('Command argv: ', argv)
    if (!argv) {
      log.error('InitCommand类的参数不能为空！')
    }
    if (!isArray(argv)) {
      log.error('InitCommand类的参数必须是数组！')
    }
    if (argv.length < 1) {
      log.error('InitCommand类的参数必须是不为空的数组！')
    }

    this._argv = argv
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve()
      chain = chain.then(() => this.checkNodeVersion())
      chain = chain.then(() => this.initArgs())

      // 执行用户自定义的
      chain = chain.then(() => this.init())
      chain = chain.then(() => this.exec())

      chain.catch(err => {
        log.error(err.message)
      })
    })
  }

  // 检查node 版本号
  checkNodeVersion() {
    // 获取当前版本号
    const currentVersion = process.version
    // 要求的最低版本号
    const lowestVersion = LOWEST_NODE_VERSION 
    
    if (!semver.gte(currentVersion, lowestVersion)) {
      throw new Error(colors.red(`cjx-cli 需要安装 v${lowestVersion} 以上版本的 Node.js`))
    }
  }

  initArgs() {
    // this._cmd = this._argv[this._argv.length - 1]
    this._argv = this._argv.slice(0, this._argv.length - 1)
    // console.log('initArgs', this._argv)
  }

  init() {
    throw new Error('init必须实现')
  }

  exec() {
    throw new Error('exec必须实现')
  }
}

// function command() {
//     // TODO
// }

module.exports = {
  Command
}